from functools import wraps
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect
from django.contrib import messages


def role_required(allowed_roles):
    """角色权限装饰器"""
    def decorator(view_func):
        @wraps(view_func)
        @login_required
        def _wrapped_view(request, *args, **kwargs):
            if not hasattr(request.user, 'userprofile'):
                messages.error(request, '用户配置不完整，请联系管理员')
                return redirect('profile')
            
            user_role = request.user.userprofile.role
            if user_role not in allowed_roles:
                raise PermissionDenied('您没有权限访问此页面')
            
            return view_func(request, *args, **kwargs)
        return _wrapped_view
    return decorator


def supervisor_required(view_func):
    """主管权限装饰器"""
    return role_required(['supervisor', 'hr', 'admin'])(view_func)


def hr_required(view_func):
    """人事权限装饰器"""
    return role_required(['hr', 'admin'])(view_func)


def admin_required(view_func):
    """管理员权限装饰器"""
    return role_required(['admin'])(view_func)
